#include "scImserial.h"

char sData[100];
char *pImCmd;
char *pImParam;
#define ELEMENTS_NUM(x) (sizeof(x)/sizeof(x[0]))

int fImBase(char *cImPar)
{
	printf("input char : %s\r",cImPar);
	return 0;
}

int fDummy()
{
	return 0;
}

int fDummy_param(char *cImPar)
{
    return 0;
}

int fShow_help(char *cImPar);

int fImInitSerial()
{
    // USART initialization
    // Communication Parameters: 8 Data, 1 Stop, No Parity
    // USART Receiver: On
    // USART Transmitter: On
    // USART Mode: Asynchronous
    // USART Baud Rate: 9600
    UCSRA=0x00;
    UCSRB=0x18;
    UCSRC=0x86;
    UBRRH=0x00;
    UBRRL=0x33;
    return 0;
}

static struct fuctions_s
{
    char *name;
	int (*openfunc)();
    int (*testfunc)(char *cImPar);
	int (*closefunc)();
}functionality[] =
{
	{"base", fImHWInit,fImBase,fDummy},
	{"help", fDummy,fShow_help,fDummy},
	{"UART", fImInitSerial,fDummy_param,fDummy},
	{"send_lcd", fImInitLcd,fImSendLcd,fDummy},
	{"read_ping", fDummy,fImCsReadPing,fDummy},
	{"set_referensi", fDummy,fImCsChangeRef,fDummy},
	{"set_ketinggian", fDummy,fImCsChangeHigh,fDummy},
	{"show_setting", fDummy,fImCsShowSetting,fDummy}
};

int fShow_help(char *cImPar)
{
    int index;               
    printf("Available command : \r");
    for(index = 0; index < ELEMENTS_NUM(functionality); ++index)
    {
        printf(" - %s",functionality[index].name); printf("\r");
    }
    return 0;
}

void fImCli()
{
        // Place your code here  
        unsigned char len;
        int index;
        for(index = 0; index < ELEMENTS_NUM(functionality); ++index)
        {
            functionality[index].openfunc();
        }
        while (1)
          {                           
            printf("#8535> ");
            gets(sData,100);
            len = strlen(sData);
            sData[len-1] = 0;
            sData[len] = 0;
            pImCmd = strtok(sData," ");     
            for(index = 0; index < ELEMENTS_NUM(functionality); ++index)
            {
                if(strcmp(functionality[index].name, pImCmd) == 0)
                {                                 
                    pImParam=strtok(NULL, "\0");
                    if(!functionality[index].testfunc(pImParam))
                    {
                            printf(".-Success\r");
                    }
                    else
				        printf(".-Fail\r");
			        break;
                }
            }
            if(index >= ELEMENTS_NUM(functionality) && pImCmd != 0)
            {    
                printf("Command not found!\r");
            }
 	    }
}